package com.wj.sparsearray;


/**
 * @author WangJin
 * @version 1.0
 * @date 2022/4/18 9:05
 */
public class SparseArray {
    public static void main(String[] args) {
        //System.out.printf("%d\t %d\t\n",5,6);
        int chessArr[][] = new int[11][11];
        //1表示黑子，2表示篮子
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        chessArr[4][5] = 2;
        System.out.println();
        System.out.println("打印原数组！");
        for (int[] row : chessArr) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        int sum = 0;
        //先遍历二维数组，看数组有多少个非0数据
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0) {
                    sum++;
                }
            }
        }

        //创建稀疏数组
        int sparseArr[][] = new int[sum+1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        //遍历二维数组，将非0的数存入sparseArr数组中
        int count = 0;
        for (int i = 1; i <11 ; i++) {
            for (int j = 0; j <11 ; j++) {
                if(chessArr[i][j]!=0){
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr[i][j];
                }
            }
        }

        //遍历稀疏数组
        System.out.println("稀疏数组");
        for(int i = 0;i<sparseArr.length;i++){
            System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
        }

        //将稀疏数组还原原来数组
        int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
        //将稀疏数组的值复制原来数组
        for(int i = 1;i < sparseArr.length;i++){
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        System.out.println("恢复打印数组");
        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }
}